package com.xinyue.dz.dao.impl;

import com.xinyue.dz.bean.User;
import com.xinyue.dz.dao.UserDao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xinyue.dz.bean.Organization;

@Repository
public class UserDaoImpl implements UserDao {
	@Autowired
    private SessionFactory factory;
    
	//默认方法
	@Override
	public void save(User entity) {
		factory.getCurrentSession().save(entity);
	}
	
	@Override
	public Integer deleteById(int userId) {
		Query q = factory.getCurrentSession().createQuery("delete User where userId=?");
		q.setParameter(0, userId);
		return q.executeUpdate();
	}
	
	@Override
	public void update(User entity) {
		factory.getCurrentSession().update(entity);
	}
	
	@Override
	public void saveOrUpdate(User entity) {
		factory.getCurrentSession().saveOrUpdate(entity);
	}
	
	@Override
	public User queryById(int userId) {
		Query q = factory.getCurrentSession().createQuery("from User where userId=?");
		q.setParameter(0, userId);
		return (User) q.uniqueResult();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<User> queryAll(int begin, int count) {
		Query q = factory.getCurrentSession().createQuery("from User");
		q.setFirstResult(begin);
		q.setMaxResults(count);
		return q.list();
	}
	
	@Override
	public Long queryCount() {
		return (Long) factory.getCurrentSession().createQuery("select count(*) from User").uniqueResult();
	}
	
	@Override
	public Organization queryOrganizationByOrgId(int orgId) {
		Query q = factory.getCurrentSession().createQuery("from Organization where orgId=:orgId");
		q.setInteger("orgId", orgId);
		return (Organization) q.uniqueResult();
	};
}